package com.fenghuajueli.libbasecoreui.utils

import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import java.util.concurrent.TimeUnit


object ArticleUtils {

    private const val ARTICLE_BASE_URL = "https://video.54yks.cn/"
    private val articleApi by lazy { createApi<ArticleApiService>(ARTICLE_BASE_URL) }

    fun getArticleList(category: String) = flow<List<Article>> {
        emit(articleApi.getArticleList(category = category).data.data_list)
    }.catch { emptyList<Article>() }


    private interface ArticleApiService {
        @GET("api/v1/article")
        suspend fun getArticleList(
            @Query("category") category: String,
            @Query("page") page: Int = 1,
            @Query("page_size") pageSize: Int = 200,
        ): ArticleResult
    }

    private inline fun <reified T> createApi(baseUrl: String): T {
        val okHttpClientBuilder =
            OkHttpClient.Builder()
                .readTimeout(15000, TimeUnit.MILLISECONDS)
                .connectTimeout(15000, TimeUnit.MILLISECONDS)

        if (AppConfigInfo.APP_DEBUG) {
            okHttpClientBuilder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        }

        val retrofit = Retrofit.Builder()
            .client(okHttpClientBuilder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(baseUrl)
            .build()
        return retrofit.create(T::class.java)
    }

    private data class ArticleResult(
        val code: Int,
        val `data`: Data,
        val msg: String
    ) {
        data class Data(
            val data_list: List<Article>,
            val total: Int
        )
    }

    data class Article(
        val article_link: String,
        val category: String,
        val cover: String?,
        val create_time: String,
        val id: Int,
        val keyword: String,
        val remark: String,
        val status: Int,
        val title: String?
    )
}










